﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Ionic.Zlib;

namespace Skyhook.Core
{
    public static class StreamFactory
    {
        const int CopyBufferSize = 1024;

        static Dictionary<string, string> FileMapping = new Dictionary<string, string>();

        public static void Initialize(string path)
        {
            string[] filenames = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories).ToArray();

            foreach (string filename in filenames)
            {
                string assetname = Path.GetFileName(filename);
                if(!FileMapping.ContainsKey(assetname))
                {
                    FileMapping.Add(assetname, filename);
                }
            }
        }

        public static string GetFullFileName(string filename)
        {
            if (FileMapping.ContainsKey(filename))
            {
                return FileMapping[filename];
            }

            return null;
        }

        public static Stream Create(string filename)
        {
            if(FileMapping.ContainsKey(filename))
            {
                FileStream result = new FileStream(FileMapping[filename], FileMode.Open);
                return result;
            }

            return null;
        }

        public static Stream CreateGZip(string filename)
        {
            Stream compressed = Create(filename);

            if (compressed != null)
            {
                MemoryStream result = new MemoryStream();
                ZlibStream zipstream = new ZlibStream(result, CompressionMode.Decompress, true);

                CopyStream(compressed, zipstream);

                compressed.Close();
                zipstream.Close();

                return result;
            }

            return null;
        }

        static void CopyStream(Stream src, Stream dest)
        {
            byte[] buffer = new byte[CopyBufferSize];
            int len = src.Read(buffer, 0, buffer.Length);
            while (len > 0)
            {
                dest.Write(buffer, 0, len);
                len = src.Read(buffer, 0, buffer.Length);
            }
            dest.Flush();
        }
    }
}
